<script lang="ts" setup>
import { ref } from 'vue'
import { getRoleListApi } from '@/api/setting'
import type { SettingList } from '@/types/setting'
import { getUserInfoApi } from '@/api/user'
import { assignRoleApi } from '@/api/employees'
import { ElMessage } from 'element-plus'

// 接收父组件传递过来的id
const props = defineProps<{ userId: string }>()

// 控制弹框的隐藏显示
const showDialog = ref(false)
const roleList = ref<SettingList[]>()
const roleIdList = ref<string[]>([])
const isLoading = ref<boolean>(false)
const showDialogFn = async () => {
  isLoading.value = true
  showDialog.value = true
  // 获取所有角色权限
  const res = await getRoleListApi({ page: 1, pagesize: 999999 })
  roleList.value = res.data.rows
  // 回显当前用户的角色权限
  const result = await getUserInfoApi(props.userId as string)
  roleIdList.value = result.data.roleIds
  isLoading.value = false
}

// 确认更新角色权限
const confirmAddRole = async () => {
  await assignRoleApi({ id: props.userId, roleIds: roleIdList.value })
  ElMessage.success('分配角色成功')
  closeDialog()
}

defineExpose({
  showDialogFn
})

//关闭弹框
const closeDialog = () => {
  showDialog.value = false
}
</script>

<template>
  <div class="assign-role">
    <el-dialog title="分配角色" v-model="showDialog" :close-on-click-modal="false">
      <el-checkbox-group v-model="roleIdList" v-loading="isLoading">
        <el-checkbox v-for="item in roleList" :key="item.id" :label="item.id" border>{{ item.name }}</el-checkbox>
      </el-checkbox-group>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeDialog">取消</el-button>
          <el-button type="primary" @click="confirmAddRole"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped></style>
